package com.example.TestCode.JavaBasics;
import java.lang.Cloneable;

public class CopyExample {
    public static void main(String[] args) throws CloneNotSupportedException {
        //克隆地址，没有引用类型
        Address address1 = new Address("安徽","亳州");
        Address address2 = (Address) address1.clone();//抛异常、类型转化
        System.out.println(address2.province+address2.city);
        // 浅克隆
        Staff s1 = new Staff("lisa",21,address1);
        Staff s2 = (Staff) s1.clone(); //抛异常、类型转化
        System.out.println(s1.address == s2.address);//没有重写clone方法，浅拷贝,结果为true

        // 深克隆
        Staff s3 = (Staff) s1.clone();//抛异常、类型转化
        System.out.println(s1.address==s3.address);//重写了clone方法，深拷贝，结果为false
        
    }
}
class Staff implements Cloneable{ //Cloneable接口里面一个方法也没有啊，重写的Object的clone方法
    public String name;
    public int age;
    public Address address;

    public Staff(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 方式一：
        Staff staff1 = new Staff(name,age, (Address) address.clone());
        // 方式二：
        Staff staff2 = (Staff) super.clone();
        staff2.address = (Address) this.address.clone();
        return staff2;
    }
}
class Address implements Cloneable {
    public String province;
    public String city;

    public Address(String province, String city) {
        this.province = province;
        this.city = city;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}
